﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DokanNetMirror.MemoryFS;

namespace MediaFS.Data
{
    public class MemoryFolder : MemoryItem
    {
        private volatile List<MemoryItem> _children;
        public MemoryFolder(MemoryFolder parent, string name)
            : base(parent, name)
        {
            Attributes = FileAttributes.Directory;
        }

        public virtual List<MemoryItem> Children
        {
            get
            {
                if(_children==null)
                {
                    lock (this)
                    {
                        if(_children==null)
                        {
                            _children = new List<MemoryItem>();        
                        }
                    }
                }
                return _children;
            }
        }

        public MemoryFolder GetFolderByPath(string path)
        {
            if (path.Equals(FullPath, StringComparison.OrdinalIgnoreCase)) return this;

            return (from MemoryFolder folder in (from c in Children
                                                 where c is MemoryFolder
                                                 select c)
                    select folder.GetFolderByPath(path)).FirstOrDefault(child => child.Exists());
        }

        public void CreatePath(string path)
        {
            var pathParts = path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (pathParts.Length <= 0) return;
            var searchResult = 
                from c in Children
                where c is MemoryFolder 
                      && c.Name.Equals(pathParts[0], StringComparison.OrdinalIgnoreCase)
                select (c as MemoryFolder);

            var newFolder = searchResult.Any() ? searchResult.First() : new MemoryFolder(this, pathParts[0]);

            if (pathParts.Length <= 1) return;
            var subPath = path.Remove(0, pathParts[0].Length + 1);
            newFolder.CreatePath(subPath);
        }

        public MemoryFile FetchFile(string name)
        {
            var files =
                from c in Children 
                where c is MemoryFile && c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)
                select c as MemoryFile;

            return files.Any() ? files.First() : null;
        }
    }
}
